$package("itsm.cim") ;
$import("common.config.dictionary.dataDictionaryUtil");
$import("common.security.userUtil");
$import('itsm.itsop.selectCompany');
$import("common.tools.event.eventAttachment");
$import('common.config.attachment.chooseAttachment');
$import('common.knowledge.knowledgeTree');
$import('common.security.includes.includes');
$import('common.config.category.serviceCatalog');
$import('itsm.cim.cimCommon');
$import("common.eav.attributes");

$import('common.config.formCustom.formControl');
$import('common.config.formCustom.formControlImpl');
$import('common.security.xssUtil');
/**  
 * @fileOverview 配置项添加
 * @author wing
 * @version 1.0  
 */  
 /**  
 * @author QXY  
 * @constructor configureItemAdd
 * @description 配置项添加
 * @date 2015-10-17
 * @since version 1.0 
 */
itsm.cim.editCimFormCustom=function(){
	//加载标识
	this.loadAttachmentFlag="0";
	
	return{
		/**
		 * 编辑配置项
		 */
		editConfigureItems:function(){
			$.each($("#editCim_formField_from :input[attrType=Lob]"),function(index,obj){
				var oEditorObj = CKEDITOR.instances[$(obj).attr("id")];
				$(obj).val(trim(oEditorObj.getData()));
			});
			$.each($("#editCim_tabs form :input[attrType=Lob]"),function(index,obj){
				var oEditorObj = CKEDITOR.instances[$(obj).attr("id")];
				$(obj).val(trim(oEditorObj.getData()));
			});
			var validate = true;
			$.each($("#editCim_tabs form"),function(index,obj){
				 if(!$(obj).form('validate')){
					 validate = false ;
				 }
			});
			if($('#editCim_formField_from').form('validate') && validate){
//				if($('#ci_edit_eavAttributet_form').form('validate')){
					//if($('#configureItemEdit_hardware form').form('validate')){
						startProcess();
						itsm.cim.ciCategoryTree.getFormAttributesValue("#configureItemEdit_panel form");
						itsm.cim.ciCategoryTree.getFormAttributesValue("#editCim_tabs form");
						$.each($("#editCim_formField_from input[attrtype='String']"),function(ind,val){
							$(this).val(common.security.xssUtil.html_encode($(this).val()));
						});
						$.each($("#editCim_tabs form input[attrtype='String']"),function(ind,val){
							$(this).val(common.security.xssUtil.html_encode($(this).val()));
						});
						var _params = $('#configureItemEdit_panel form,#editCim_tabs form').serialize();
						if($('#configureItemEdit_panel #ci_edit_cino_old').val()!=$('#configureItemEdit_panel #ci_edit_cino').val()){
							$.post('ci!existCIByCiNo.action','ciQueryDTO.cino='+$('#ci_edit_cino').val(),function(data){
								if(data){
									msgAlert(i18n['err_ciNoExist'],'info');
									endProcess();
								}else{
									$.post('ci!cItemUpdate.action',_params,function(data){
										endProcess();
										basics.tab.tabUtils.closeTab(i18n['ci_editConfigureItem']);
										basics.tab.tabUtils.addTab(i18n['ci_configureItemAdmin'],'../pages/itsm/cim/configureItem.jsp?');
										$('#configureGrid').trigger('reloadGrid');
										msgShow(i18n['editSuccess'],'show');
										if ($('#itsmMainTab').tabs('exists',i18n.ci_configureItemAdmin)){
											itsm.cim.leftMenu.companyStat();
											basics.showChart.cimShowChart();
										}
									});
								}
							})
						}else{
							$.post('ci!cItemUpdate.action',_params,function(data){
								endProcess();
								basics.tab.tabUtils.closeTab(i18n['ci_editConfigureItem']);
								basics.tab.tabUtils.addTab(i18n['ci_configureItemAdmin'],'../pages/itsm/cim/configureItem.jsp?');
								$('#configureGrid').trigger('reloadGrid');
								msgShow(i18n['editSuccess'],'show');
								if ($('#itsmMainTab').tabs('exists',i18n.ci_configureItemAdmin)){
									itsm.cim.leftMenu.companyStat();
									basics.showChart.cimShowChart();
								}
							});
						}
					/*}else{
						$('#editCim_tabs').tabs('select', ci_edit_hardware);
					}*/
//				}else{
//					msgAlert(i18n.eavAttributet_notNull,'info');
//					$('#editCim_tabs').tabs('select', ci_edit_eavAttributet);
//				}
			}	
		},
		/**@description 配置项分类选择窗口打开*/
		focusInit:function(){
			configureItemTree();
			windows('configureItemEditCategory',{width:400,height:400});
		},
		/**
		 * 加载tab的select事件
		 */
		tabClick:function(){
	        $('#editCim_tabs').tabs({
	            onSelect:itsm.cim.editCimFormCustom.tabClickEvents  
	        });
		},
		/**@description 点击tab后，根据tab标题加载不同的数据*/
		tabClickEvents:function(title){
			if(title==i18n.softSettingParam){
				itsm.cim.editCimFormCustom.getSoftAttachmentBySoftId($('#editCiId').val());
			}
		},
		/**
		 * @description 选择请求者.
		 */
		selectCICreator:function(userName){
			common.security.userUtil.selectUser(userName,'','','fullName');
		},
		/**
		 * @description 返回列表
		 */
		returnConfigureItemList:function(){
			basics.tab.tabUtils.addTab(i18n['ci_configureItemAdmin'],'../pages/itsm/cim/configureItem.jsp');
		},
		/**
		 * 点击上传附件按钮
		 */
		configureitemEdit_uploadifyUpload:function(){
			if($('#configureItemEdit_effect_fileQueue').html()!="")
				$('#configureItemEdit_effect_file').uploadifyUpload();
			else
				msgShow(i18n['msg_add_attachments'],'show');
		},
		/**
		 * @description 查找配置项附件信息
		 **/
		getSoftAttachmentBySoftId:function (ciId)
		{
			if(loadAttachmentFlag=="1")
				 return false;
			loadAttachmentFlag="1";
			//$('#edit_uploadedSoftAttachments').html('');
			if(ciId==undefined){}else{
				var url = 'ci!getSoftAttachmentByCiId.action?ciEditId='+ciId;
				$.post(url,function(res)
				{
					var arr=res;
					if(arr!=null){
						for(var i=0;i<arr.length;i++){
							var file=arr[i].url;
							var fileName=file.substring(file.lastIndexOf("/")+1);
							var fileFix=fileName.substring(fileName.indexOf(".")).toLowerCase();
							var iconUrl="<img src='../images/attachicons/";
							if(fileFix==".rar"){
								iconUrl=iconUrl+"rar.gif'";
							}
							if(fileFix==".zip"){
								iconUrl=iconUrl+"zip.gif'";
							}
							if(fileFix==".gif"||fileFix==".jpg"||fileFix==".bmp"||fileFix==".png"){
								iconUrl=iconUrl+"image.gif'";
							}
							if(fileFix==".doc"||fileFix==".docx"||fileFix==".xls"||fileFix==".ppt"||fileFix==".pptx"||fileFix==".xlsx"){
								iconUrl=iconUrl+"msoffice.gif'";
							}
							if(fileFix==".pdf"){
								iconUrl=iconUrl+"pdf.gif'";
							}
							if(fileFix==".swf"){
								iconUrl=iconUrl+"flash.gif'";
							}
							if(fileFix==".txt"){
								iconUrl=iconUrl+"text.gif'";
							}
							else{
								iconUrl=iconUrl+"unknown.gif'";
							}
							iconUrl=iconUrl+" width='14px' height='14px'/>&nbsp;";
							
							$('#edit_uploadedSoftAttachments').append("<span id=edit_uploadedSoftAttachments_ID_"+arr[i].aid+">"+iconUrl+"<a target='_blank' href=attachment!download.action?downloadAttachmentId="+arr[i].aid+">"+arr[i].attachmentName+"</a>&nbsp;&nbsp;<a href=JavaScript:itsm.cim.editCimFormCustom.deleteAttachement('edit_uploadedSoftAttachments','"+ciId+"','"+arr[i].aid+"')>"+i18n['deletes']+"</a><br/></span>");
			
						}
					}
				});
				}
		},
		/**
		 * @description 删除附件
		 **/
		deleteAttachement:function(id,kid,aid){
			msgConfirm(i18n['msg_msg'],'<br/>'+i18n['msg_confirmDelete'],function(r){
					var _url = "ci!deleteSoftAttachement.action?ciEditId="+kid+"&aid="+aid;
					$.post(_url,function(){
						$('#edit_uploadedSoftAttachments_ID_'+aid).remove();
						msgShow(i18n['deleteSuccess'],'show');
					});
			});
		},
		loadCimFormHtmlByFormId:function(res,htmlDivId){
			itsm.cim.cimCommon.initDefaultFormByAttr(htmlDivId);
			itsm.cim.cimCommon.initDefaultForm(htmlDivId);
			itsm.cim.cimCommon.changeCompany();
			$('#'+htmlDivId).prepend($('#ci_edit_addfeld').html());
			itsm.cim.editCimFormCustom.setEditCimCss(res);
			itsm.cim.cimCommon.setfieldOptionsLobCss('#'+htmlDivId);
			//itsm.cim.cimCommon.setCimParamValueToOldFormByDataDictionaray('#'+htmlDivId,res);
			$.parser.parse($('#'+htmlDivId));
			common.config.formCustom.formControlImpl.formCustomInit('#'+htmlDivId);
			itsm.cim.cimCommon.setCimParamValueToOldForm('#'+htmlDivId,res);
			if(!res.isNewForm){
				$.post("ciCategory!findByCategoryId.action","categoryNo="+res.categoryNo,function(data){
					common.eav.attributes.findAttributeByCim_New(ciEditId,'itsm.request',data,'ciDto',res.attrVals,function(json){
						if(json!=undefined){
							var jsonStr=common.security.base64Util.encode(JSON.stringify(json));
							$('#'+htmlDivId).append(common.config.formCustom.formControlImpl.editHtml(jsonStr,htmlDivId));
						}
						itsm.cim.cimCommon.setCimParamValueToOldFormByDataDictionaray('#'+htmlDivId,res);
						$.parser.parse($('#'+htmlDivId));
						endProcess();
					});
				});	
				
			}else{
				itsm.cim.cimCommon.setCimParamValueToOldFormByDataDictionaray('#'+htmlDivId,res);
				endProcess();
			}
		},
		initEditTabs:function(formData,ciData){
			var data = formData.formCustomTabsDtos;
			for ( var i = 0; i < data.length; i++) {
				var tabId =data[i].tabId;
				var name =data[i].tabName;
				var attrNos = data[i].tabAttrNos;
				var htmlDivId = 'editCim_tabs_formField_'+tabId;
				var formCustomContents = common.config.formCustom.formControlImpl.editHtml(data[i].tabAttrsConent,htmlDivId);
				$('#editCim_tabs').tabs('add',{
					title:name,
					cache:"true",
					content:"<form><div id='"+htmlDivId+"' style='width: 90%;margin:0 auto;'>"+formCustomContents+"</div></form>",
					active: 1
				});
				itsm.cim.cimCommon.setCimFormValues(ciData,'#'+htmlDivId,'itsm.configureItem',formData.eavNo,ciData.attrVals,function(){
					common.config.formCustom.formControlImpl.formCustomInit('#'+htmlDivId);
				});
				itsm.cim.editCimFormCustom.showTabsCss('#'+htmlDivId);
				$.parser.parse($('#'+htmlDivId));//加上这句，必填才有用
			}
		},
		showTabsCss:function(htmlDIvId){
			$(htmlDIvId).find("div[class=field_options] div[class=label]:odd").css("border-left","none");
			var leng = $(htmlDIvId).find("div[class='field_options_2Column field_options']").length;
			if(leng>0){
				$.each($(htmlDIvId).find("div[class='field_options']"),function(ind,obj){
					$(obj).attr("class","field_options_2Column field_options");
					$(obj).find("div[class='field']").attr("class","field_lob");
				});
				//$("#editField_requestServiceDirs").parent().prev().attr("style","");
				$.each($(htmlDIvId).find("div[class='field_options_lob field_options']"),function(ind,obj){
					$(obj).children(":first").css("height","292px");
				});
				$.each($(htmlDIvId+" div[class='field_options_2Column field_options']"),function(ind,obj){
					$(obj).find("div[class='field_lob']").css("margin-top","10px");
				});
			}else{
				$.each($(htmlDIvId).find("div[class='field_options_lob field_options']"),function(ind,obj){
					$(obj).children(":first").css("height","302px");
				});
				$.each($(htmlDIvId).find("div[class='field_options_lob field_options']"),function(ind,obj){
					$(obj).find("div[class='field_lob']").css("margin-left","5px");
				});
			}
		},
		findByciId:function(){
			var htmlDivId = "editCim_formField";
			$('#'+htmlDivId).html("");
			var url = 'ci!findById.action?ciEditId='+ciEditId;
			$.post(url, function(res){
				$.post("formCustom!findFormCustomByCiCategoryNo.action","formCustomDTO.ciCategoryNo="+res.categoryNo,function(data){
					if(data!=null&&data.formCustomContents!=""){
						itsm.cim.editCimFormCustom.initEditTabs(data,res);
						var formCustomContents = common.config.formCustom.formControlImpl.editHtml(data.formCustomContents,htmlDivId);
						$('#'+htmlDivId).html(formCustomContents);
						$('#'+htmlDivId).prepend($('#ci_edit_addfeld').html());
						itsm.cim.cimCommon.setCimFormValues(res,'#'+htmlDivId,'itsm.configureItem',data.eavNo,res.attrVals,function(){
							common.config.formCustom.formControlImpl.formCustomInit('#'+htmlDivId);
							endProcess();
						});
						$.parser.parse($('#'+htmlDivId));
						itsm.cim.editCimFormCustom.setEditCimCss(data);
					}else{
						var durl='common/config/formCustom/ciDefaultField_Old.jsp';
						if(res.isNewForm){
							durl='common/config/formCustom/ciDefaultField.jsp';
						}
						$("#"+htmlDivId).load(durl,function(){
							itsm.cim.editCimFormCustom.loadCimFormHtmlByFormId(res,htmlDivId);
						});
					}
				});
			});
		},
		setEditCimCss:function(res){
			itsm.cim.cimCommon.bindAutoCompleteToCim('editCim_formField');
			//itsm.cim.editCimFormCustom.setEditCimParamValue(res);重要
			
			$("#editCim_formField").find("div[class=field_options] div[class=label]:odd").css("border-left","none");
			if(res.isShowBorder){
				$("#editCimFormCustom").attr("href","../styles/common/editCimFormCustom.css");
				$("#editCim_formField :input").css("margin-top","0px");
			}else{
				$("#editCimFormCustom").attr("href","../styles/common/editCimFormCustom-no.css");
				$("#editCim_formField").find(":input").not(".control").css("margin-top","10px"); 
			}
			if(res.isNewForm){
				$("#cimEdit_isNewForm").val(true);
			}else{
				$("#cimEdit_isNewForm").val(false);
			}
			//设置所属客户不可编辑,并且移除图标
			$("#editCim_formField #ci_add_companyNo").next().remove();
			$("#editCim_formField #ci_add_companyName").attr("disabled",true).css("width","90%");
			
			itsm.cim.editCimFormCustom.oneRowCss(res);
			
		},
		oneRowCss:function(res){
			if(res.isShowBorder=="1"){
				var leng = $("#editCim_formField").find("div[class='field_options_2Column field_options']").length;
				if(leng>0){
					$.each($("#editCim_formField").find("div[class='field_options']"),function(ind,obj){
						$(obj).attr("class","field_options_2Column field_options");
						$(obj).find("div[class='field']").attr("class","field_lob");
					});
					//$("#editField_requestServiceDirs").parent().prev().attr("style","");
					$.each($("#editCim_formField").find("div[class='field_options_lob field_options']"),function(ind,obj){
						$(obj).children(":first").css("height","292px");
					});
					$.each($("div[class='field_options_2Column field_options']"),function(ind,obj){
						$(obj).find("div[class='field_lob']").css("margin-top","10px");
					});
				}else{
					$.each($("#editCim_formField").find("div[class='field_options_lob field_options']"),function(ind,obj){
						$(obj).children(":first").css("height","302px");
					});
					$.each($("#editCim_formField").find("div[class='field_options_lob field_options']"),function(ind,obj){
						$(obj).find("div[class='field_lob']").css("margin-left","5px");
					});
				}
			}else{
				var leng = $("#editCim_formField").find("div[class='field_options_2Column field_options']").length;
				if(leng>0){
					$.each($("#editCim_formField").find("div[class='field_options']"),function(ind,obj){
						$(obj).attr("class","field_options_2Column field_options");
						$(obj).find("div[class='field']").attr("class","field_lob");
					});
					$.each($("#editCim_formField").find("div[class='field_options_lob field_options']"),function(ind,obj){
						$(obj).find("div[class='field_lob']").css("margin-left","7px");
					});
				}else{
					$.each($("#editCim_formField").find("div[class='field_options_lob field_options']"),function(ind,obj){
						$(obj).find("div[class='field_lob']").css("margin-left","4px");
					});
				}
				$.each($("div[class='field_options_2Column field_options']"),function(ind,obj){
					$(obj).find("div[class='field_lob'] :input").css("margin-top","0px");
				});
			}
		},
		
		/**
		 * 初始化数据
		 */
		init:function(){
			//绑定日期控件
//			DateBox(['configureItem_add_buyDate','configureItem_add_arrivalDate','warningDate','configureItem_edit_warningDate','ci_edit_eavAttributet_Date','wasteTime_edit','borrowedTime_edit','expectedRecoverTime_edit','recoverTime_edit','operatingSystem_installDate_edit','operatingSystem_lastBootUpTime_edit']);
			itsm.cim.includes.includes.loadSelectCIIncludesFile();//加载选择配置项
			common.security.includes.includes.loadSelectUserIncludesFile();//加载用户选择
			$("#configureItemEdit_loading").hide();
			$("#configureItemEdit_panel").show();
			
			itsm.cim.editCimFormCustom.tabClick();
			$('#ci_edit_useName_select').click(function(){common.security.userUtil.selectUser('#ci_edit_useName','#ci_edit_useNameId','','fullName',$('#ci_edit_companyNo').val())});//选择使用者
			$('#ci_edit_owner_select').click(function(){common.security.userUtil.selectUser('#ci_edit_owner','#ci_edit_ownerId','','fullName',$('#ci_edit_companyNo').val())});//选择负责人
			$('#ci_edit_originalUser_select').click(function(){common.security.userUtil.selectUser('#ci_edit_originalUser','#ci_edit_originalUserId','','fullName',$('#ci_edit_companyNo').val())});//选择原使用者
			$('#configureItem_edit_department').click(function(){//选择部门
				common.security.organizationTreeUtil.showAll_2('#index_assignGroup_window','#index_assignGroup_tree','#configureItem_edit_department','',$('#ci_edit_companyNo').val());
			});
			//编辑
			$('#itemEditSave').click(function(){
				itsm.cim.editCimFormCustom.editConfigureItems();
			});
			$('#ci_loc_edit').click(function(){
				itsm.cim.cimCommon.selectCimLocation('#ci_loc_edit','#ci_locid_edit',this);
			});
			setTimeout(function(){
				//getUploader('上传文件文本ID','上传后返回的信息字符串','显示上传成功的附件','');
				getUploader('#configureItemEdit_effect_file','#configureItemEdit_effect_attachmentStr','#conmfigureItemEdit_effect_success_attachment','configureItemEdit_effect_fileQueue', function(){
				    common.tools.event.eventAttachment.saveAttachment('show_configureItemEdit_effectAttachment',$('#editCiId').val(),'itsm.configureItem','configureItemEdit_effect_attachmentStr',true);
				});
				//getUploader('#edit_uploadSoftAttachments','#editConfigureItem_Softattachments','#edit_uploadedSoftAttachments','editConfigureItem_SoftfileQueue');
				//initFileUpload("_CiEdit",$('#editCiId').val(),"itsm.configureItem",fullName,"show_configureItemEdit_effectAttachment","configureItemEdit_effect_attachmentStr");
				//initFileUpload("_CiEditSoft","","","","","#editConfigureItem_Softattachments","#edit_uploadedSoftAttachments");
			},0);
			common.tools.event.eventAttachment.showAttachment('show_configureItemEdit_effectAttachment',$('#editCiId').val(),'itsm.configureItem',true);
			$('#edit_ci_service_add').click(function(){//关联服务目录
				common.config.category.serviceCatalog.selectServiceDir('#edit_ci_serviceDirectory_tbody');
			});
			itsm.cim.editCimFormCustom.findByciId();
			$('#edit_ci_relatedService_checked').click(function(){checkAll('edit_ci_relatedService_checked','edit_ci_relatedService','ciDto.serviceDirectoryNos');});
		}
	};
 }(); 
 //加载初始化数据
 $(document).ready(itsm.cim.editCimFormCustom.init);